<?php

namespace osc\mobile\controller;
use think\Db;
use think\Session;
use think\Loader;
use think\File;

class Ticket extends MobileBase
{
	protected function _initialize()
	{

		parent::_initialize();						
		define('UID',is_login());	
		//手机版
		if(!UID){		
			$this->redirect('login/login');					
		}

		if (!Session::has("username")) {

            $this->redirect('login/login');

        }
    }

    /*
      1.进入配票页面
	  2.判断是否有正在处理的排单
    */
    function ticket()
    {
		$error=null;
		if($this->request->isPost()){
			$data = $this->request->param();
			$rt = Db::name('token')->where('token',$data['__token__'])->find();
			if($rt)
			{
				$this->error('请勿重复提交');
			}
			$ticket = Db::name('ticket_matching')->where('id',$data['id'])->find();
//			print_r($ticket);exit;
			if($ticket['state'] != 0 && $ticket['state'] != 4){
				$this->error('当前状态不符合提交');
			}
			//判断是否有图片在
			$seq = Db::name('rang_order_img')->where('rang_order_id',$data['id'])->where('seq_id',1)->select();
			if(!$seq)
			{
				$this->error('没有上传图片');
			}
			$map = [
					'submit_time'	=> time(),
					'state'			=> 1
			];
			Db::name('ticket_matching')->where('id',$data['id'])->update($map);

			$this->success('提交成功','rang/fin');
		}
        $username = session("username");
        $user = Db::name('member')->where('username',$username)->find();
        //var_dump($user);

		$ticket = Db::name('ticket_matching')->where('username',$username)->find();

		if(!$ticket)
		{
			if($user['user_rang_num']>0)
			{

				//插入一条新的
				$ticket_date['username'] = $username;
				$ticket_date['id_name']  = $user['idcardname'];
				$ticket_date['id_card']  = $user['idcard'];
				$ticket_date['vip_level']  = $user['user_rang_num'];
				$ticket_date['num']  = $user['user_rang_num'];
				$ticket_date['total_time'] = 1;
				Db::name('ticket_matching')->insert($ticket_date);

				Db::name('member')->where('username',$username)->setDec('user_rang_num',$ticket_date['num']);

			}

		}

		if($ticket)
		{
			if($user['user_rang_num']>0)
			{

				//插入一条新的
				$ticket_date['username'] = $username;
				$ticket_date['id_name']  = $user['idcardname'];
				$ticket_date['id_card']  = $user['idcard'];
				$ticket_date['vip_level']  = $user['user_rang_num'];
				$ticket_date['num']  = $user['user_rang_num'];
				$ticket_date['total_time'] =	$ticket['total_time']+1;
				Db::name('ticket_matching')->insert($ticket_date);

				Db::name('member')->where('username',$username)->setDec('user_rang_num',$ticket_date['num']);

			}

		}	
		//获取当前入金交易所
		$ex = Db::name('exchage_variety')->where('use_state',1)->find();
		if($ex)
		{
			$exchange = Db::name('exchange_house')->where('id',$ex['exchange_id'])->find();
		}

		$max_id = Db::name('ticket_matching')->where('username',$username)->max('id');
		$tick = Db::name('ticket_matching')->where('id',$max_id)->find();
		$price = $tick['num'] * 22800;


		//$price = $ticket['num'] * 22800;


		$img = Db::name('rang_order_img')->where(['rang_order_id'=>$tick['id'],'seq_id'=>1])->select();
		$this->assign('img',$img);
		$this->assign('ticket',$tick);
		$this->assign('price',$price);
		$this->assign('exchange',$exchange);
		$this->assign('top_title','配票');

		return $this->fetch();
    }


    function ticket_commit()
    {
    	if(request()->isPost())
    	{
    		//获取id号
    		$id = 1;
    		//上传图片

    		//设置交易品种
    		//获取交易品种

    		$ex = Db::name('exchage_variety')->where('state',1)->find();

    		if($ex)
    		{
    			$exchang['exchange_id'] = $ex['id'];
    			//$exchang['exchange_variety_id'] = $ex['exchange_id'];
    			Db::name('ticket_matching')->where('id',$id)->update($exchang);
    		}

    		//


    	}

		$this->assign('ticket',$ticket);
		
		return $this->fetch();
	}

	/**
	 * 提交凭证
	 * @return mixed
	 */
	function ticket_delivery()
	{
		$mobile = session("username");
		$username = $mobile;
		$user = Db::name('member')->where('username',$mobile)->find();
		if($user['user_level']==0)
		{
			$this->redirect('user/index');
		}
		$error = null;

		$rang_order= Db::query('select * from osc_rang_order where id = (select max(id) from osc_rang_order where username = '.$mobile.' and rang = 2) ');

		$rang_order1= Db::query('select * from osc_rang_order where id = (select max(id) from osc_rang_order where username = '.$username.'  and rang = 1)');
		var_dump($rang_order1);




		//$ret = Db::name('rang_order')->where('id',$dt1['trade_id'])->update($dt1['trade_id']);

		if(request()->isPost()){
			$data=input('post.');

			$data['token']  = input('post.__token__/s', null);
			$rt = Db::name('token')->where('token',$data['token'])->find();
			$to['token'] = $data['token'];
			$error = null;
			if($rt)
			{
				$error = "请勿重复提交！";
			}else
			{
				$rt = Db::name('token')->insert($to);
			}

			//对数据进行校验

			//var_dump($data);
			//die;

			if(!$error)
			{

				Db::startTrans();

				try
				{

					if($rang_order)
					{

						//判断是否有图片在


						$seq = Db::name('rang_order_img')->where('rang_order_id',$rang_order[0]['id'])->where('seq_id',2)->find();
						if(!$seq)
						{
							$error="没有上传图片";
						}

						if(!$error){
							if($rang_order[0]['delivery']==0)
							{

								//$rang['trade_dt']=$data['trade_dt'];
								$rang['delivery']=1;

								$rang['commit_dt']=time();


								$rt = Db::name('rang_order')->where('id',$rang_order[0]['id'])->find();

								$ret=Db::name('rang_order')->where('id',$rang_order[0]['id'])->update($rang);

								//$this->redirect('financing/frist_delivery');
							}
							//var_dump($rang_order);
							//判断当前记录在审核时，不能处理该订单,只有回退的订单才能处理
							if($rang_order[0]['delivery']==3)
							{

								$rang['delivery']=1;

								$rang['commit_dt']=time();

								//die;

								$ret=Db::name('rang_order')->where('id',$rang_order[0]['id'])->update($rang);
								//$this->redirect('financing/frist_delivery');

							}
						}
					}

					Db::commit();
					//$this->redirect('financing/frist_delivery');
				}
				catch (\Exception $e) {

					Db::rollback();
					return array('error'=>$e->getMessage());

				}
			}

		}

		//die;
		//查询交易所
		$exchange = Db::name('exchange_house')->where('state',1)->select();
		//查询交易品种
		$variety = Db::name('exchage_variety')->where('state',1)->select();


		$rang_order= Db::query('select * from osc_rang_order where id = '.$rang_order[0]['id']);
		//var_dump($rang_order);

		$data['delete_url']='';
		$data['upload_url']=url('financing/upload');
		//删除
		$data['delete_url']=url('financing/delete');

		$img = Db::name('rang_order_img')->where('rang_order_id',$rang_order[0]['id'])->where('seq_id',2)->select();
		//var_dump($img);
		$dt = time();
		$endflag=0;

		if($dt>$rang_order[0]['sell_time'])
		{
			$endflag=1;
		}
		$this->assign('img',$img);
		$this->assign('endflag',$endflag);
		$this->assign('exchange',$exchange);
		$this->assign('rang_order',$rang_order);
		$this->assign('error',$error);
		$this->assign('variety',$variety);
		$this->assign('top_title','第一轮提货处理');
		$this->assign('data',$data);
		$this->assign('userinfo',Db::name('member')->where('uid',UID)->find());
		$this->assign('l_url','/mobile/financing/frist');
		$this->assign('SEO',['title'=>'第一轮提货处理-'.config('SITE_TITLE')]);
		$this->assign('flag','user');
		return $this->fetch();

	}

	/**
	 * 图片上传
	 * @return null
	 */
	public function upload(){
		$json = null;
		$mobile = session("username");
		$user = Db::name('member')->where('username',$mobile)->find();
		if($user['user_level']==0)
		{
			$json['error'] = '请重新登录';
		}
		if(!$mobile)
		{
			$json['error'] = '请重新登录';
		}

		$data = input('post.');
		$file = request()->file('file');
		if (empty($file)) {
			$json['error'] = '请选择上传文件';
		}
		//移动到框架应用根目录/public/uploads/ 目录下
		$url = "/public/uploads/images/" . UID . "/" . $data['id']. "/";
		$PATH = ROOT_PATH . "public/uploads/images/" . UID . "/" . $data['id']. "/";
		if (!is_dir($PATH)) {
			mkdir($PATH, 0777, true);
		}//判断目录是否存在，不存在则创建
		$info = $file
				->validate(['size'=>5242880,'ext'=>'jpeg,jpg,png,gif'])
				->move($PATH);
		if ($info) {
			$img_time_name = $info->getSaveName();
			$img_name = $info->getFilename();
			if($this->isImg($PATH.$img_time_name)){
				$map = [
					'rang_order_id' => $data['id'],
					'img_path'		=> $url.$img_time_name,
					'file_name'		=> $img_name,
					'seq_id'		=> $data['type']
				];
				Db::name('rang_order_img')->insertGetId($map);
				$json['success'] = '上传成功';
			}else{
				$json['error'] = '只支持jpeg,jpg,png,gif格式图片';
			}

		} else {
			//上传失败获取错误信息
			$json['error'] = $file->getError();
		}
		return $json;
	}

	/**
	 * 验证图片
	 * @param $fileName
	 * @return bool|int
	 */
	function isImg($fileName)
	{
		$file  = fopen($fileName, "rb");
		$bin  = fread($file, 2);

		fclose($file);
		$strInfo = @unpack("C2chars", $bin);
		$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
		$fileType = '';

		if($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/)
		{
			return $typeCode;
		}
		else
		{
			// echo '"仅允许上传jpg/jpeg/gif/png格式的图片！';
			return false;
		}
	}

	/**
	 * 删除图片和文件夹
	 * @return array
	 */
	public function img_delete(){

		$mobile = session("username");
		$user = Db::name('member')->where('username',$mobile)->find();
		if($user['user_level']==0)
		{
			$json['error'] = '请重新登录';
		}

		if(!$mobile)
		{
			$json['error'] = '请重新登录';
		}

		$json =[];

		$post=input('post.');

		if (isset($post['path'])) {
			$paths = $post['path'];
		} else {
			$json['error'] = '非法操作';

			return $json;
		}
		$id = "";

		if (isset($post['id'])) {
			$id = $post['id'];
		} else {
			$json['error'] = '非法操作';

			return $json;
		}

		// Loop through each path to run validations
		foreach ($paths as $path) {

			//查询对应的记录是否存在
			$user = Db::name('rang_order_img')->where('img_path',$path)->find();

			if($user)
			{
				Db::name('rang_order_img')->where('img_path',$path)->where('rang_order_id',$id)->delete();
			}
		}
		$json['success'] ='删除成功';

		return $json;
	}


}
